package project.android;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class NewTaskPage extends Activity{
	
	 
	public void onCreate(Bundle savedInstanceState) {
			
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.new_task);
	         
	}
	    
	public void saveTaskButtonOnClick(View view){
			
			String name = ((EditText) findViewById(R.id.nameIn)).getText().toString();
			String description = ((EditText) findViewById(R.id.descriptionIn)).getText().toString(); 
			String deadline = ((EditText) findViewById(R.id.deadlineIn)).getText().toString();
			String assignedby = ((EditText) findViewById(R.id.assignedbyIn)).getText().toString();
			String groupname = ((EditText) findViewById(R.id.groupnameIn)).getText().toString();
		
			UUID uuid = UUID.randomUUID();
			String _uuid = uuid.toString();
			
			String[] test = deadline.split("/");
			
			if(test.length != 3 || test[0].length() != 4 || test[1].length() != 2 || test[2].length() != 2){
				
				SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy/MM/dd");
			    Date now = new Date();
			    deadline = sdfDate.format(now).replaceAll("-","/");
				
			}
			
			String toBeInserted = name+","+description+","+deadline+","+assignedby+","
				+groupname+",,0,0,"+_uuid+",0"; 
					
			//database connection to insert newly created task
			DatabaseConnection db = new DatabaseConnection(this); 
	        db.connectDatabase("TaskBoard","Tasks");
	        db.insert(toBeInserted);
			db.close();	
	        
	        
			//send the new task to server
			
			try{
				Synchronized th = new Synchronized();
				th.db = new DatabaseConnection(this);
				th.run();
	        }
	        catch(Exception e){
	        	
	        	new AlertDialog.Builder(this)
	        	.setTitle("Server Connection Error")
	        	.setMessage(e.getMessage().toString())
		        .setNeutralButton(android.R.string.cancel,
		            new DialogInterface.OnClickListener() {
			           public void onClick(DialogInterface dialog, int whichButton){
			        	   
			        	   finish();
			           
			           }
		        })
		        .show();
	        	
	        }
			
			Intent i = new Intent(NewTaskPage.this, ManageTasks.class);
			startActivity(i);
	      	
	}
	
	
}
